package leetcode.code1104;

import java.util.ArrayList;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	List<Integer> ans;
	int label;

	public List<Integer> pathInZigZagTree(int label) {
		this.label = label;
		int level = (int) Math.ceil(Math.log10(label) / Math.log10(2));
		if ((Math.pow(2, level) == label)) {
			level++;
		}
		int to = this.val(label, level);
		ans = new ArrayList<>();
		int high = 1 << level - 1;
		this.f(to, high, 1, 1);
		return ans;
	}

	private int val(int label, int level) {
		if ((level & 1) == 1) {
			return label;
		}
		int min = (int) Math.pow(2, level - 1), max = (int) Math.pow(2, level) - 1;
		return max - label + min;
	}

	private void f(int to, int high, int level, int val) {
		int cur = this.val(val, level);
		this.ans.add(cur);
		if (cur == label) {
			return;
		}
		high >>= 1;
		if ((to & high) == 0) {// 左
			this.f(to, high, level + 1, val << 1);
		} else {
			this.f(to, high, level + 1, val << 1 | 1);
		}
	}

	@Override
	public void debug4() {
		H.compare(H.str2array3("[1,2,6,10,26]"), this.pathInZigZagTree(16));
		H.compare(H.str2array3("[1,2,6,10,26]"), this.pathInZigZagTree(26));
		H.compare(H.str2array3("[1,3,4,14]"), this.pathInZigZagTree(14));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		System.out.println(Math.sqrt(1) + " , " + Math.ceil(Math.sqrt(1)));
		System.out.println(Math.sqrt(3) + " , " + Math.ceil(Math.sqrt(3)));
		System.out.println(Math.sqrt(6) + " , " + Math.ceil(Math.sqrt(6)));
		System.out.println(Math.sqrt(16) + " , " + Math.ceil(Math.sqrt(16)));
		System.out.println(Math.pow(2, 4) + " , " + Math.ceil(Math.pow(2, 4)));
	}

}
